package miku.firstgame.ui.card
{
	import com.saia.starlingPunk.SPEntity;

	import flash.geom.Point;
	import flash.security.CertificateStatus;

	import feathers.controls.Button;
	import feathers.core.FeathersControl;

	import miku.firstgame.constrants.EventConstants;
	import miku.firstgame.model.Me;
	import miku.firstgame.model.gold.CardPlaceVo;
	import miku.firstgame.model.gold.ToolPlaceVo;
	import miku.firstgame.model.gold.card.BombCard;
	import miku.firstgame.model.gold.card.MapCard;
	import miku.firstgame.model.gold.card.RoadCard;
	import miku.firstgame.model.gold.interfaces.ICard;
	import miku.firstgame.model.gold.util.CardUtil;
	import miku.firstgame.world.GameRoomWorld;

	import starling.animation.Tween;
	import starling.core.Starling;
	import starling.display.Sprite;
	import starling.events.Event;
	import starling.events.Touch;
	import starling.events.TouchEvent;
	import starling.events.TouchPhase;

	/**
	 *卡牌
	 * */
	public class CardGroupUI extends SPEntity
	{
		//public var cardMap:CardMap;  

		public var cards:Vector.<ICard>;

		public var cardUIs:Vector.<CardUI>;

		public var startPoint:Point;

		/**
		 * 用于翻转卡牌
		 * */
		public var toggleCardButton:Button;
		/**
		 * 用于丢弃卡牌
		 * */
		public var removeCardButton:Button;

		public var buttonContainer:Sprite;

		public function CardGroupUI(cards:Vector.<ICard>)
		{
			super(0, 0, "cardGroup");
			this.cards = cards;
			cardUIs = new Vector.<CardUI>;
		}

		override public function added():void
		{
			super.added();
			setupGraphic();
		}

		private function initCardOperateUI():void
		{

			toggleCardButton = new Button();
			toggleCardButton.label = "翻";
			toggleCardButton.padding = 1;
			toggleCardButton.setSize(CardUI.WIDTH / 2, CardUI.WIDTH / 2);
			toggleCardButton.addEventListener(Event.TRIGGERED, onToggleCardButtonClick);
			//this.addChild(toggleCardButton);

			removeCardButton = new Button();
			removeCardButton.label = "丢";
			removeCardButton.padding = 1;
			removeCardButton.setSize(CardUI.WIDTH / 2, CardUI.WIDTH / 2);
			//this.addChild(removeCardButton);
			removeCardButton.x = toggleCardButton.width;
			removeCardButton.y = 0;
			removeCardButton.addEventListener(Event.TRIGGERED, onRemoveCardButtonClick);

			buttonContainer = new Sprite();
			buttonContainer.addChild(toggleCardButton);
			buttonContainer.addChild(removeCardButton);
			//buttonContainer.visible = true;
			//this.world.addChild(buttonContainer);
		}

		private function onRemoveCardButtonClick(e:Event):void
		{
			var cardUI:CardUI = (e.target as Button).parent.parent as CardUI;
			if (cardUI)
			{
				moveLeftCard(cardUI);
				this.world.dispatchEventWith(EventConstants.USER_DROP_A_CARD, false, cardUI);
			}
		}

		private function onToggleCardButtonClick(e:Event):void
		{
			var cardUI:RoadCardUI = (e.target as Button).parent.parent as RoadCardUI;
			if (cardUI)
			{
				cardUI.toggleCard();
			}
		}

		private function setupGraphic():void
		{
			if (cards)
			{
				var length:int = cards.length;
				for (var i:int = 0; i < length; i++)
				{
					var card:ICard = cards[i];
					addSimpleCard(card, i * (CardUI.WIDTH + 5) + this.x, this.y);
				}
			}
			initCardOperateUI();
		}

		public function addCard(card:ICard):void
		{
			var length:int = cards.length;
			addSimpleCard(card, length * (CardUI.WIDTH + 5) + this.x, this.y);
			cards.push(card);
		}

		/**
		 * 单纯的只用于郑家一张卡片
		 * */
		private function addSimpleCard(card:ICard, cx:Number, cy:Number):void
		{
			var ui:CardUI = CardUtil.getCardUIByCard(card);
			ui.x = cx;
			ui.y = cy;
			ui.addEventListener(TouchEvent.TOUCH, onTouch);
			this.world.add(ui);
			cardUIs.push(ui);
		}

		private function clearButton():void
		{
			if (buttonContainer && buttonContainer.parent)
			{
				buttonContainer.parent.removeChild(buttonContainer);
			}
		}

		private function onTouch(event:TouchEvent):void
		{
			/**
			 * TODO 如果卡片已经移除，需要将卡片弹回
			 * */
			if (!Me.Instace.canDoAction)
			{
				return;
			}

			var card:CardUI = event.currentTarget as CardUI;
			if (null == card)
			{
				return;
			}

			var startTouch:Touch = event.getTouch(card, TouchPhase.BEGAN);
			if (startTouch)
			{
				card.parent.setChildIndex(card, card.parent.numChildren - 1);
				card.isMoved = true;
				startPoint = new Point(card.x, card.y);
			}

			var endTouch:Touch = event.getTouch(card, TouchPhase.ENDED);
			if (endTouch)
			{
				releaseCard(card);
			}

			var touches:Vector.<Touch> = event.getTouches(card, TouchPhase.MOVED);
			if (touches.length >= 1)
			{
				clearButton();
				if (touches.length == 1)
				{
					// one finger touching -> move
					var delta:Point = touches[0].getMovement(parent);
					card.x += delta.x;
					card.y += delta.y;
					cardMoving(card);
				}
				else
				{

				}
			}

			else if (touches.length == 0)
			{
				var overTouch:Touch = event.getTouch(card, TouchPhase.HOVER);
				if (overTouch) //over
				{
					//trace("overTouch");

//					buttonContainer.visible = true;
//					buttonContainer.x = card.x; 
//					buttonContainer.y = card.y;
					if (null == buttonContainer.parent)
					{
						if (card is RoadCardUI)
						{
							toggleCardButton.visible = true;
						}
						else
						{
							toggleCardButton.visible = false;
						}
						card.addChild(buttonContainer);
					}
					trace("overTouch");

				}
				else //out
				{
					if (!(event.target is Button))
					{
						clearButton();
					}

					//buttonContainer.visible = false;
					trace("not overTouch");
				}
			}

//			if (touch && touch.tapCount == 2)
//				parent.addChild(this); // bring self to front

			// enable this code to see when you're hovering over the object
			// touch = event.getTouch(this, TouchPhase.HOVER);            
			// alpha = touch ? 0.8 : 1.0;
		}

		private function cardMoving(card:CardUI):void
		{
			var map:CardMap = (this.world as GameRoomWorld).cardMap;
			map.cardMoveOnMap(card);
		}

		/**
		 * 当card被移除的时候，移动剩下的卡片
		 * */
		private function moveLeftCard(card:CardUI):void
		{
			clearButton();
			removeCard(card); //移除卡片 
			for each (var c:CardUI in cardUIs)
			{
				if (c.x > startPoint.x)
				{
					var tween:Tween = new Tween(c, 0.2);
					tween.onComplete = onCardMoveComplete;
					tween.onCompleteArgs = [c];
					tween.moveTo(c.x - CardUI.WIDTH - 5, c.y);
					Starling.juggler.add(tween);
					c.touchable = false;
				}
			}
		}

		/**
		 *
		 * */
		private function releaseCard(card:CardUI):void
		{

			var gw:GameRoomWorld = (this.world as GameRoomWorld);
			var map:CardMap = gw.cardMap;

			card.isMoved = false;
			//todo。如果和相应的卡片碰撞，则

			/**
			 * 是否需要将卡片返回
			 * */
			var needToReturn:Boolean = true;

			if (card is ToolCardUI)
			{
				var selectSeat:UserSeat;
				for each (var seat:UserSeat in gw.seats)
				{
					if (seat.selected)
					{
						selectSeat = seat;
						break;
					}
				}
				if (selectSeat)
				{
					needToReturn = false;
					var tvo:ToolPlaceVo = new ToolPlaceVo(card as ToolCardUI, selectSeat);
					this.world.dispatchEventWith(EventConstants.USE_TOOL_ON_USER, false, tvo);
					moveLeftCard(card);
				}
			}
			else if (card is RoadCardUI || card.card is BombCard || card.card is MapCard)
			{
				var placePoint:Point = map.cardMoveOnMap(card);
				if (placePoint)
				{
					needToReturn = false;
					var cvo:CardPlaceVo = new CardPlaceVo(card, placePoint);
					this.world.dispatchEventWith(EventConstants.CARD_PLACE_ON_MAP, false, cvo);
					moveLeftCard(card);
				}

				map.hideValidateArea();
			}

			if (needToReturn && startPoint)
			{
				var tween:Tween = new Tween(card, 0.3);
				tween.onComplete = onCardMoveComplete;
				tween.onCompleteArgs = [card];
				tween.moveTo(startPoint.x, startPoint.y);
				Starling.juggler.add(tween);
				card.touchable = false;
			}
		}

		private function onCardMoveComplete(card:CardUI):void
		{
			card.touchable = true;
		}

		public function removeCard(card:CardUI):void
		{
			card.removeEventListener(TouchEvent.TOUCH, onTouch);
			var index:int = cards.indexOf(card.card);
			if (-1 != index) //从集合中移除
			{
				cards.splice(index, 1);
			}
			index = cardUIs.indexOf(card);
			if (-1 != index)
			{
				cardUIs.splice(index, 1);
			}
//			if (card.parent == this) // 从子元素中移除
//			{
//				this.removeChild(card);
//			}

		}

		override public function removed():void
		{
			removeChildren(0, -1, true);
			super.removed();
		}

		override public function update():void
		{
			super.update();

		}
	}
}
